<?php

namespace App\Services;

use App\Models\CancelUserModel;
use App\Models\DictItemModel;

use App\Models\ServoRegistModel;
use App\Models\StoreManagementModel;
use App\Models\StoreModel;
use App\Models\TagsModel;
use App\Models\UserAssetsModel;
use App\Models\UserAtLogModel;
use App\Models\UserAuthModel;
use App\Models\UserCharmedModel;
use App\Models\UserClientModel;
use App\Models\UserFavorModel;
use App\Models\UserLoveInfoModel;
use App\Models\UserModel;
use App\Models\UserMtLogModel;
use App\Models\UserPushMsgModel;
use App\Models\UserSickModel;
use Carbon\Carbon;
use Framework\BaseService;
use Framework\ModelEncryptionTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Kra8\Snowflake\Snowflake;

class UserService extends BaseService
{
    use ModelEncryptionTrait;


    /**
     * 注销账户记录
     * @param $user_id
     * @return bool
     * @throws \Throwable
     */
    public function cancelUser($user_id)
    {
        $e = CancelUserModel::query()->where(['user_id'=>$user_id])->exists();
        if($e)
        {
            $this->retError('您已提交注销，请勿重复操作');
        }
        $modle = new CancelUserModel();
        $modle->user_id =$user_id;
        return $modle->saveOrFail();
    }



    public function editPassword(string $user_id, string $password, string $password_confirmation, string $old_password)
    {
        if ($password !== $password_confirmation) {
            $this->retError('两次输入的密码不一致');
        }

        $info = UserModel::findOrFail($user_id);
        if (!Hash::check($old_password, $info->password)) {
            $this->retError('原密码不正确');
        }

        if (Hash::check($password, $info->password)) {
            $this->retError('新密码不能与原密码一样');
        }

        $info->password = Hash::make($password);
        $info->saveOrFail();

        return true;

    }

    public function editUserInfo($user_id, $params)
    {
        return UserModel::query()->where('id', $user_id)->update($params);
    }





    public function forgetLoginPassword($phone, $code, $password, $password_confirmation)
    {
        if ($password !== $password_confirmation) {
            $this->retError('两次输入的密码不一致');
        }

        //验证短信验证码
        app(SmsService::class)->checkSmsCode($phone, $code);

        //获取手机号,进行短信验证
        $phone_str = $this->encryptAttribute($phone);
        $info = UserModel::query()->where('phone',$phone_str)->first();

        if (!$info) {
            $this->retError('未找到账户信息');
        }


        //保存登录密码
        $info->password = Hash::make($password);
        $info->saveOrFail();

        return true;
    }

    public function getUserInfo($user_id)
    {
        $userinfo = UserModel::query()->where("id", $user_id)->first();
        $assets = UserAssetsModel::query()->where('user_id', $user_id)->first();
        if (!$assets) {
            $data['mt'] = 0;
            $data['at'] = 0;
        } else {
            $data['mt'] = $assets->mt;
            $data['at'] = $assets->at + $assets->lock_at;

        }
        $data['userinfo'] = $userinfo;
        return $data;
    }


    public function addTags($type, $name)
    {
        //用户增加标签
        //标签库维护
        $model = TagsModel::query()->firstOrNew(['type' => $type, 'name' => $name]);

        return $model;
    }


    /**
     * 上传头像
     * @param $user_id
     * @param $avatar
     * @return bool
     */
    public function uploadAvatar($user_id, $avatar)
    {
        $user = UserModel::query()->where('id', $user_id)->first();
        if (!$user) {
            $this->retError("该用户不存在");
        }
        $user->avatar = $avatar;
        $user->save();
        return true;
    }








    public function getUserDetails($user_id)
    {
        return UserModel::query()->where('id', $user_id)->first();
    }

    public function myMtLog($user_id, $page, $size)
    {
        return UserMtLogModel::query()->where('user_id', $user_id)->forPage($page, $size)->get();
    }

    public function myAtLog($user_id, $role_type, $page, $size)
    {
        return UserAtLogModel::query()->where('user_id', $user_id)->where('role_type', $role_type)->forPage($page, $size)->get();
    }





    /**
     * @param $user_id
     * @param $send_title
     * @param $send_content
     * @return mixed
     * @throws \Exception
     */
    public function pushToSingleByCid($user_id, $send_title, $send_content)
    {
        $snowflake = app(Snowflake::class);
        $send_id = $snowflake->next();

        //数据推送至信息列表
        $user_push_msg = new UserPushMsgModel();
        $user_push_msg->type = 2;
        $user_push_msg->send_id = $send_id;
        $user_push_msg->user_id = $user_id;
        $user_push_msg->title = $send_title;
        $user_push_msg->msg = $send_content;
        $user_push_msg->is_read = 0;
        $user_push_msg->save();

        //查询客户端
        $client_id = UserClientModel::where('user_id', $user_id)->where('status', 1)->value('clientID');
        if (!$client_id) {
            Log::info($user_id . '-客户端未登录，无法推送信息');
            return false;
        }

        return app(ClientMsgPushService::class)->pushToSingleByCid($send_id, $client_id, $send_title, $send_content);
    }


    /**
     * 用户-账户-申请删除
     * @param $user_id
     * @return bool
     * @throws \Throwable
     */
    public function applyDelMime($user_id)
    {
        $user_info = UserModel::find($user_id);
        try {
            DB::transaction(function () use ($user_id, $user_info) {
                $now = Carbon::now();
                //查询用户信息
                $user_info->del_phone = $user_info->phone;//删除手机号标记
                $user_info->del_time = $now;//删除时间
                $user_info->phone = $now->timestamp;//修改手机号
                $user_info->true_name = '';
                $user_info->nickname = '';
                $user_info->avatar = '';
                $user_info->wechat_account = '';
                $user_info->wechat_openid = '';
                $user_info->birthday = '1000-01-01';//放到1000年以前
                $user_info->sex = 2;
                $user_info->status = 1;

                $user_info->saveOrFail();



                //删除实名信息
                UserAuthModel::query()->where('user_id', $user_id)->delete();

            });
        } catch (\Exception $e) {
            Log::warning('删除账户失败：' . $user_id);
            $this->retError('系统暂不支持申请账户删除');
        }

        return true;
    }



}
